package com.myProxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.Test;

import java.lang.reflect.Method;

/**
 * @Auther: Liang
 * @Date: 2024/5/14 - 05 - 14 - 15:27
 * @Description: com.myProxy.cglib
 * @version: 1.0
 */
public class CGLIBProxy {

    @Test
    public void cglib(){
        Target target = new Target(); //创建目标对象
        Enhancer enhancer = new Enhancer();   //创建增强器
        enhancer.setSuperclass(Target.class); //设置父类
        enhancer.setCallback(new MethodInterceptor() { //设置回调
            @Override
            public Object intercept(Object o, Method method, Object[] objects,
                                    MethodProxy methodProxy) throws Throwable {
                System.out.println("前置代码增强2....");
                Object invoke = method.invoke(target, objects);
                System.out.println("后置代码增强2....");
                return invoke;
            }
        });
        Target proxy = (Target) enhancer.create(); //创建代理对象
        proxy.marry();
    }
}
